package guda.house.web.action.front.wx.payback;

import guda.grape.autogen.common.page.BizResult;
import guda.house.biz.FrontFeeBiz;
import guda.house.biz.config.WeixinConfig;
import guda.house.biz.enums.WxPayStatusEnum;
import guda.house.biz.helper.alipay.AlipayHelper;
import guda.house.biz.helper.weixin.WeixinUtil;
import guda.house.biz.helper.weixin.form.WeixinNotifyResponse;
import guda.house.dal.dao.WxPayOrderDAO;
import guda.house.dal.dataobject.WxPayOrderDO;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * Created by well on 16/5/29.
 */
@Controller
@RequestMapping(value = "front")
public class WeixinBack {

    private Logger log = LoggerFactory.getLogger(WeixinBack.class);
    @Autowired
    private FrontFeeBiz frontFeeBiz;
    @Autowired
    private WxPayOrderDAO wxPayOrderDAO;

    @RequestMapping(value = "wx/payback/weixinBack.htm")
    public String back(HttpServletRequest request, ModelMap modelMap){
        ServletInputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            WeixinNotifyResponse weixinNotifyResponse = new WeixinNotifyResponse();
            Map<String, String> param = WeixinUtil.parse2Map(sb.toString());

            String orginalSign = param.get("sign");
            param.remove("sign");
            if (param == null || !"SUCCESS".equals(param.get("return_code"))) {
                log.error("weixin notify error:" + sb.toString());
                weixinNotifyResponse.setReturn_code("FAIL");
                weixinNotifyResponse.setReturn_msg("数据解析错误");
                modelMap.put("response", weixinNotifyResponse.toXML());
                return "front/wx/payback/weixinBack.vm";
            }
            //校验签名

            String queryString = AlipayHelper.createQueryString(param);
            queryString = queryString + "&key=" + WeixinConfig.appSecret;
            log.info("weixin check sign:" + queryString);
            String sign = DigestUtils.md5Hex(queryString).toUpperCase();
            if (!sign.equals(orginalSign)) {
                log.error("weixin notify error 签名错误:" + sb.toString());
                weixinNotifyResponse.setReturn_code("FAIL");
                weixinNotifyResponse.setReturn_msg("签名错误");
                modelMap.put("response", weixinNotifyResponse.toXML());
                return "front/wx/payback/weixinBack.vm";
            }
            String out_trade_no = param.get("out_trade_no");
            if (out_trade_no.length() == 31) {
                out_trade_no = out_trade_no.substring(0, 28);
            }
            if (out_trade_no == null) {
                return "front/wx/payback/weixinBack.vm";
            }
            String result_code = param.get("result_code");
            if (!"SUCCESS".equals(result_code)) {
                log.error("weixin notify error 支付未完成:" + sb.toString());
                weixinNotifyResponse.setReturn_code("SUCCESS");
                weixinNotifyResponse.setReturn_msg("OK");
                modelMap.put("response", weixinNotifyResponse.toXML());
                return "front/wx/payback/weixinBack.vm";
            }

            WxPayOrderDO wxPayOrderByOrderNo = wxPayOrderDAO.getWxPayOrderByOrderNo(out_trade_no);
            if (wxPayOrderByOrderNo.getPayStatus().intValue() != WxPayStatusEnum.init.getVal()) {
                log.error("订单已经处理，收到微信回调：out_trade_no＝[" + out_trade_no + "],trade_status=[" + out_trade_no + "]，当前订单状态:" + wxPayOrderByOrderNo.getPayStatus());

                weixinNotifyResponse.setReturn_code("SUCCESS");
                weixinNotifyResponse.setReturn_msg("OK");
                modelMap.put("response", weixinNotifyResponse.toXML());
                return "front/wx/payback/weixinBack.vm";

            }
            //如果支付成功
            //1,发送短信通知供应商和平台
            //2,跳转到车主信息录入页

            BizResult bizResult = frontFeeBiz.paySuccess(wxPayOrderByOrderNo.getOrderId(), out_trade_no);
            if (bizResult.success) {
                log.warn("回调处理成功：out_trade_no＝[" + out_trade_no + "]");
                weixinNotifyResponse.setReturn_code("SUCCESS");
                weixinNotifyResponse.setReturn_msg("OK");
                modelMap.put("response", weixinNotifyResponse.toXML());
                return "front/wx/payback/weixinBack.vm";
            } else {
                log.warn("回调处理失败：out_trade_no＝[" + out_trade_no + "]，code=" + bizResult.code);
                weixinNotifyResponse.setReturn_code("FAIL");
                weixinNotifyResponse.setReturn_msg("处理失败");
                modelMap.put("response", weixinNotifyResponse.toXML());
                return "front/wx/payback/weixinBack.vm";
            }


        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {

                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {

                }
            }
        }
        return "front/wx/payback/weixinBack.vm";
    }
}
